import axios from 'axios'
import merge from 'merge'
import { Toast } from 'vant';
import C from './constant';

const CancelToken = axios.CancelToken
const Fetch = function(instanceConfig) {
  if (typeof instanceConfig === 'object') {
    // 配置消息提示对象
    Fetch.$Message = instanceConfig.message || ''
    return Fetch.init(instanceConfig)
  } else {
    console.error('初始化参数需要为对象！')
  }
}
// 初始化
Fetch.init = function(instanceConfig) {
  Fetch.$Message = instanceConfig.message || ''
  // 创建axios实例，默认已json对象形式接收数据(application/json)
  const instance = axios.create(merge.recursive({
    timeout: 30000,
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    }
  }, instanceConfig))
  // request拦截器相关处理
  instance.interceptors.request.use(config => {
    config.headers['x-access-token'] = sessionStorage.getItem('token')
    return config
  }, error => {
    return Promise.reject(error)
  })

  // response拦截器相关处理
  instance.interceptors.response.use(response => {
    // 请求超时
    if (response.data.message && response.data.message.indexOf('connect ECONNREFUSED') !== -1) {
      Fetch.message.handle('网络请求超时!')
    }
    if (response.data.code === '0' || response.data.code === 0) {
      // 正常
      return response.data
    } else {
      // 通过config里面的message来判断是否显示
      if (typeof response.config.message === 'boolean' && !response.config.message) {
        return response.data
      } else {
        Fetch.message.handle(response.data.message, response.config.interval)
        return Promise.reject(new Error(response.data.message))
      }
    }
  }, error => {
    let message = ''
    if (error.config && typeof error.config.message === 'boolean' && !error.config.message) {
      return Promise.reject(error)
    }
    if (error.response && error.response.data) {
      if (error.response.data.errMsg && error.response.data.errMsg.includes('Unable to find instance')) {
        message = error.message.replace(/.*\s(.*)/gi, '$1') + '服务不可用'
      } else {
        message = error.response.data.errMsg
      }
      Fetch.message.handle(message, error.config.interval)
      return Promise.reject(new Error(error.response.data))
    } else {
      if (error.message) {
        if (error.message.includes('timeout')) {
          message = '网络请求超时'
        } else {
          message = error.message
        }
        Fetch.message.handle(message, error.config.interval)
      }
      return Promise.reject(error)
    }
  })
  instance.source = function() {
    return CancelToken.source()
  }
  return instance
}
// 直接挂载axios
Fetch.axios = axios
Fetch.message = {
  time: '',
  content: '',
  interval: 3000,
  set(message) {
    this.content = message
    this.time = new Date().getTime()
  },
  handle(message, interval) {
    if (!interval) {
      interval = this.interval
    }
    if (new Date().getTime() - this.time < interval && this.content === message) {
      // 间隔时间内信息相同，不重复显示
      return
    }
    // Fetch.$Message && Fetch.$Message({
    //   message: message,
    //   type: 'error'
    // })
    if (message.includes('token')) {
      // sessionStorage.clear()
      // location.href = location.origin + location.pathname
    } else {
      Toast(message || '系统走偏，请稍后！')
    }
    this.set(message)
  }
}
const Request = Fetch.init({
  baseURL: C.url.base,

})
export default Request